package cn.imatu.framework.log.integration.okhttp;

import cn.imatu.framework.core.utils.IpUtils;
import cn.imatu.framework.core.utils.spring.SpringUtils;
import cn.imatu.framework.log.common.LogCons;
import cn.imatu.framework.log.utils.BraveTracerUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request.Builder;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * OkHttp的拦截器
 * @author shenguangyang
 */
@Slf4j
public class LyLogOkHttpInterceptor implements Interceptor {

    @Override
    public Response intercept(final Chain chain) throws IOException {
        Builder builder = chain.request().newBuilder();
        String traceId = BraveTracerUtils.getTraceString();
        if (StringUtils.isNotBlank(traceId)) {
            BraveTracerUtils.addTraceId(builder::header);

            String appName = SpringUtils.getProperty("spring.application.name");
            builder.header(LogCons.PRE_APP_IP, IpUtils.getHostIp());
            builder.header(LogCons.TRACE_ID_HEADER, traceId);
            builder.header(LogCons.PRE_APP_KEY, appName);
            builder.header(LogCons.PRE_APP_HOST_NAME, IpUtils.getHostName());
        } else {
            log.debug("本地threadLocal变量没有正确传递traceId,本次调用不传递traceId");
        }

        return chain.proceed(builder.build());
    }
}